package com.hunktimes.wholesale.extension

import android.view.View
import android.widget.EditText
import android.widget.ImageView
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.hunktimes.wholesale.R
import com.hunktimes.wholesale.util.DisplayUtil
import com.hunktimes.wholesale.util.L
import com.hunktimes.wholesale.widget.EmptyCornerDrawable

/**
 * Author: Delete
 * Date: 2020/7/23 17:52
 * Description:
 *
 */



fun EditText.setAndSeletText(text: String?) {
    if (!text.isNullOrBlank()) {
        L.d("setAndSelectText -> $text")
        setText(text)
        setSelection(getText().toString().length)
    }
}

fun View.showHide(staus: Boolean) {
    if (staus)
        show()
    else
        hide()
}

fun View.hide() {
    if (this.visibility == View.VISIBLE) {
        this.visibility = View.GONE
    }
}

fun View.show() {
    if (this.visibility == View.GONE) {
        this.visibility = View.VISIBLE
    }
}

fun ImageView.setImageUrl(url: String) {
    Glide.with(this)
        .load(url)
        .placeholder(R.drawable.glide_holder)
        .error(R.drawable.glide_holder)
        .into(this)
}

fun ImageView.setImageUrl(url: String, radius: Float) {
    val radiusPx = DisplayUtil.dp2px(context, radius)
    val empty = EmptyCornerDrawable(
        ContextCompat.getColor(context, R.color.bgGray_F7F5F6),
        radiusPx.toFloat()
    )
    Glide.with(this)
        .load(url)
        .apply(
            RequestOptions()
                .transform(CenterCrop(), RoundedCorners(radiusPx))
        )
        .placeholder(empty)
        .error(empty)
        .into(this)
}

fun ImageView.setAvatar(url: String, radius: Float) {
    val radiusPx = DisplayUtil.dp2px(context, radius)

    Glide.with(this)
        .load(url)
        .apply(
            RequestOptions()
                .transform(CenterCrop(), RoundedCorners(radiusPx))
        )
        .placeholder(R.drawable.user_avatar_holder)
        .error(R.drawable.user_avatar_holder)
        .into(this)
}

fun String.isMobilePhone(): Boolean {
    return this.matches(
        Regex("[1][345789]\\d{9}")
    )
}

/*香港手机号码正则 ：^([6|9])\d{7}$
澳门手机号码正则：^[0][9]\d{8}$
大陆：^[1][3-8]\d{9}$
正则表达式：^[1][3-8]\d{9}$|^([6|9])\d{7}$|^[6]([8|6])\d{5}$
这是规则：
大陆：开头1 3-8号码段，后面加9位数字
香港：9或6开头后面跟7位数字
澳门：66或68开头后面跟5位数字
注意：以上表达式只验证港澳台及大陆手机号码，不包含座机小灵通及区号等验证*/
fun String.isHKPhone(): Boolean {
    return this.matches(
        Regex("[6|9]\\d{7}")
    )
}

fun String.formatePhone(): String {
    return if (this.length == 11)
        this.replaceRange(3, 7, "****")
    else this
}

fun String.isSmsCode(): Boolean {
    return this.length == 6
}